<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>维修上报系统 - 用户端</title>
    
    <!-- Vue 3 CDN -->
    <script src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.js"></script>
    
    <!-- Naive UI CDN -->
    <script src="https://cdn.jsdelivr.net/npm/naive-ui@2.34.4/dist/index.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/naive-ui@2.34.4/dist/index.css">
    
    <!-- 自定义样式 -->
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background-color: #f5f5f5;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
            padding: 20px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .form-section {
            background: white;
            padding: 24px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .section-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 16px;
            color: #333;
            border-left: 4px solid #18a058;
            padding-left: 12px;
        }
        
        .form-row {
            display: flex;
            gap: 16px;
            margin-bottom: 16px;
        }
        
        .form-item {
            flex: 1;
        }
        
        .items-table {
            margin-top: 16px;
        }
        
        .total-price {
            text-align: right;
            font-size: 18px;
            font-weight: 600;
            color: #d03050;
            margin-top: 16px;
            padding: 12px;
            background: #fef2f2;
            border-radius: 6px;
        }
        
        .submit-section {
            text-align: center;
            margin-top: 24px;
        }
        
        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }
            
            .form-row {
                flex-direction: column;
                gap: 12px;
            }
        }
    </style>
</head>
<body>
    <div id="app">
        <n-config-provider :theme="null">
            <n-message-provider>
                <app-content></app-content>
            </n-message-provider>
        </n-config-provider>
    </div>
    
    <script>
        const { createApp } = Vue;
        const { 
            NConfigProvider, 
            NMessageProvider, 
            useMessage,
            NCard,
            NForm,
            NFormItem,
            NButton,
            NSelect,
            NInput,
            NInputNumber,
            NDatePicker,
            NTable,
            NEmpty,
            zhCN,
            dateZhCN
        } = naive;
        
        // 主要内容组件
        const AppContent = {
            components: {
                NConfigProvider,
                NCard,
                NForm,
                NFormItem,
                NButton,
                NSelect,
                NInput,
                NInputNumber,
                NDatePicker,
                NTable,
                NEmpty
            },
            template: `
                <n-config-provider :locale="zhCN" :date-locale="dateZhCN">
                <div class="container">
                    <!-- 页面标题 -->
                    <div class="header">
                        <h1 style="margin: 0; color: #333;">维修上报系统</h1>
                        <p style="margin: 8px 0 0 0; color: #666;">请填写维修信息并选择维修项目</p>
                    </div>
                    
                    <!-- 基本信息 -->
                    <div class="form-section">
                        <div class="section-title">基本信息</div>
                        
                        <div class="form-row">
                            <div class="form-item">
                                <n-form-item label="选择区域" required>
                                    <n-select
                                        v-model:value="form.area_id"
                                        :options="areaOptions"
                                        placeholder="请选择区域"
                                        @update:value="onAreaChange"
                                        :loading="areasLoading"
                                    />
                                </n-form-item>
                            </div>
                            <div class="form-item">
                                <n-form-item label="维修地点" required>
                                    <n-input
                                        v-model:value="form.location"
                                        placeholder="请输入具体维修地点"
                                    />
                                </n-form-item>
                            </div>
                        </div>
                        
                        <div class="form-row">
                            <div class="form-item">
                                <n-form-item label="维修人员" required>
                                    <n-input
                                        v-model:value="form.person"
                                        placeholder="请输入维修人员姓名"
                                    />
                                </n-form-item>
                            </div>
                            <div class="form-item">
                                <n-form-item label="维修时间" required>
                                    <n-date-picker
                                        v-model:value="form.repair_date"
                                        type="date"
                                        placeholder="请选择维修时间"
                                        style="width: 100%;"
                                        :locale="dateZhCN"
                                    />
                                </n-form-item>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 维修项目 -->
                    <div class="form-section">
                        <div class="section-title">维修项目</div>
                        
                        <n-form-item label="添加维修项目">
                            <n-select
                                v-model:value="selectedItemId"
                                :options="itemOptions"
                                placeholder="请先选择区域，然后选择维修项目"
                                @update:value="addItem"
                                :loading="itemsLoading"
                                :disabled="!form.area_id"
                                filterable
                            />
                        </n-form-item>
                        
                        <div class="items-table" v-if="form.items.length > 0">
                            <n-table :bordered="true" :single-line="false">
                                <thead>
                                    <tr>
                                        <th>维修内容</th>
                                        <th>规格型号</th>
                                        <th>数量</th>
                                        <th>单位</th>
                                        <th>单价(元)</th>
                                        <th>小计(元)</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="(item, index) in form.items" :key="index">
                                        <td>{{ item.name }}</td>
                                        <td>{{ item.specification || '-' }}</td>
                                        <td>
                                            <n-input-number
                                                v-model:value="item.quantity"
                                                :min="1"
                                                :step="1"
                                                :precision="0"
                                                style="width: 80px;"
                                                @update:value="calculateTotal"
                                            />
                                        </td>
                                        <td>{{ item.unit }}</td>
                                        <td>{{ item.price }}</td>
                                        <td>{{ (item.quantity * item.price).toFixed(2) }}</td>
                                        <td>
                                            <n-button
                                                type="error"
                                                size="small"
                                                @click="removeItem(index)"
                                            >
                                                删除
                                            </n-button>
                                        </td>
                                    </tr>
                                </tbody>
                            </n-table>
                            
                            <div class="total-price">
                                总计：¥{{ form.total_price.toFixed(2) }}
                            </div>
                        </div>
                        
                        <n-empty
                            v-else
                            description="暂无维修项目"
                            style="margin: 20px 0;"
                        />
                    </div>
                    
                    <!-- 提交按钮 -->
                    <div class="submit-section">
                        <n-button
                            type="primary"
                            size="large"
                            @click="submitForm"
                            :loading="submitting"
                            :disabled="!canSubmit"
                        >
                            提交计价单
                        </n-button>
                        
                        <n-button
                            style="margin-left: 16px;"
                            @click="resetForm"
                        >
                            重置表单
                        </n-button>
                    </div>
                </div>
                </n-config-provider>
            `,
            setup() {
                const message = useMessage();
                
                // 响应式数据
                const form = Vue.ref({
                    area_id: null,
                    location: '',
                    person: '',
                    repair_date: null,
                    items: [],
                    total_price: 0
                });
                
                const areas = Vue.ref([]);
                const items = Vue.ref([]);
                const selectedItemId = Vue.ref(null);
                const areasLoading = Vue.ref(false);
                const itemsLoading = Vue.ref(false);
                const submitting = Vue.ref(false);
                
                // 计算属性
                const areaOptions = Vue.computed(() => {
                    return areas.value.map(area => ({
                        label: area.name,
                        value: area.id
                    }));
                });
                
                const itemOptions = Vue.computed(() => {
                    return items.value.map(item => ({
                        label: `${item.name} ${item.specification ? '(' + item.specification + ')' : ''} - ¥${item.price}/${item.unit}`,
                        value: item.id
                    }));
                });
                
                const canSubmit = Vue.computed(() => {
                    return form.value.area_id && 
                           form.value.location && 
                           form.value.person && 
                           form.value.repair_date && 
                           form.value.items.length > 0;
                });
                
                // 方法
                const loadAreas = async () => {
                    try {
                        areasLoading.value = true;
                        const response = await fetch('/api/areas');
                        const result = await response.json();
                        
                        if (result.success) {
                            areas.value = result.data;
                        } else {
                            message.error(result.message || '获取区域列表失败');
                        }
                    } catch (error) {
                        console.error('获取区域列表失败:', error);
                        message.error('获取区域列表失败');
                    } finally {
                        areasLoading.value = false;
                    }
                };
                
                const loadItems = async (areaId) => {
                    try {
                        itemsLoading.value = true;
                        const response = await fetch(`/api/items/${areaId}`);
                        const result = await response.json();
                        
                        if (result.success) {
                            items.value = result.data;
                        } else {
                            message.error(result.message || '获取维修项目失败');
                        }
                    } catch (error) {
                        console.error('获取维修项目失败:', error);
                        message.error('获取维修项目失败');
                    } finally {
                        itemsLoading.value = false;
                    }
                };
                
                const onAreaChange = (areaId) => {
                    if (areaId) {
                        loadItems(areaId);
                        // 清空已选择的项目
                        form.value.items = [];
                        calculateTotal();
                    }
                };
                
                const addItem = (itemId) => {
                    if (!itemId) return;
                    
                    const item = items.value.find(i => i.id === itemId);
                    if (!item) return;
                    
                    // 检查是否已添加
                    const existingIndex = form.value.items.findIndex(i => i.id === itemId);
                    if (existingIndex >= 0) {
                        message.warning('该项目已添加');
                        selectedItemId.value = null;
                        return;
                    }
                    
                    // 添加项目
                    form.value.items.push({
                        id: item.id,
                        name: item.name,
                        specification: item.specification,
                        unit: item.unit,
                        price: item.price,
                        quantity: 1
                    });
                    
                    calculateTotal();
                    selectedItemId.value = null;
                };
                
                const removeItem = (index) => {
                    form.value.items.splice(index, 1);
                    calculateTotal();
                };
                
                const calculateTotal = () => {
                    form.value.total_price = form.value.items.reduce((total, item) => {
                        return total + (item.quantity * item.price);
                    }, 0);
                };
                
                const formatDate = (timestamp) => {
                    if (!timestamp) return '';
                    const date = new Date(timestamp);
                    return date.toISOString().split('T')[0];
                };
                
                /**
                 * 提交计价单表单
                 * 使用异步方式提交，避免页面刷新
                 */
                const submitForm = async (event) => {
                    // 阻止默认的表单提交行为，避免页面刷新
                    if (event && event.preventDefault) {
                        event.preventDefault();
                    }
                    
                    try {
                        submitting.value = true;
                        
                        const submitData = {
                            area_id: form.value.area_id,
                            location: form.value.location,
                            person: form.value.person,
                            repair_date: formatDate(form.value.repair_date),
                            items: JSON.stringify(form.value.items),
                            total_price: form.value.total_price
                        };
                        
                        const response = await fetch('/api/quotations', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify(submitData)
                        });
                        
                        const result = await response.json();
                        
                        if (result.success) {
                            message.success('计价单提交成功！');
                            // 成功后保留表单内容，不进行重置
                            handleSubmitSuccess();
                        } else {
                            message.error(result.message || '提交失败');
                        }
                    } catch (error) {
                        console.error('提交失败:', error);
                        message.error('提交失败，请重试');
                    } finally {
                        submitting.value = false;
                    }
                    
                    // 确保不会有页面跳转或刷新
                    return false;
                };
                
                /**
                 * 重置表单（仅在用户手动点击重置按钮时调用）
                 * 提交成功后不再自动重置表单，保留所有内容
                 */
                const resetForm = () => {
                    form.value = {
                        area_id: null,
                        location: '',
                        person: '',
                        repair_date: null,
                        items: [],
                        total_price: 0
                    };
                    selectedItemId.value = null;
                    items.value = [];
                };
                
                /**
                 * 提交成功后的处理函数
                 * 不重置表单，保留所有内容供用户继续使用
                 */
                const handleSubmitSuccess = () => {
                    // 提交成功后不做任何重置操作
                    // 用户可以基于当前表单内容继续修改和提交
                    console.log('表单提交成功，保留所有内容');
                };
                
                // 初始化
                Vue.onMounted(() => {
                    loadAreas();
                });
                
                return {
                    form,
                    areas,
                    items,
                    selectedItemId,
                    areasLoading,
                    itemsLoading,
                    submitting,
                    areaOptions,
                    itemOptions,
                    canSubmit,
                    onAreaChange,
                    addItem,
                    removeItem,
                    calculateTotal,
                    submitForm,
                    resetForm,
                    handleSubmitSuccess,
                    zhCN,
                    dateZhCN // 中文日期本地化配置
                };
            }
        };
        
        // 创建Vue应用
        createApp({
            components: {
                NConfigProvider,
                NMessageProvider,
                AppContent
            }
        }).mount('#app');
    </script>
</body>
</html>